/**
 * @description 登录、获取用户信息、退出登录、清除accessToken逻辑，不建议修改
 */
import { getAccessToken, removeAccessToken, setAccessToken } from '@/utils/accessToken'
import { message, notification } from 'ant-design-vue'
import Cookies from 'js-cookie'
import * as authApi from '@/api/auth'
import config from '@/config'
import { get } from '@/utils'

const state = () => ({
  accessToken: Cookies.get(config.authKey),
  username: '',
  avatar: '',
  userInfo: {},
  bussinessType: null, // 业务类型
  cityInfo: null // 地市编码
})

const getters = {
  accessToken: state => state.accessToken,
  username: state => state.username,
  avatar: state => state.avatar,
  userInfo: state => state.userInfo,
  cityInfo: state => state.cityInfo
}

const mutations = {
  /**
   * @description 业务类型
   * @param {*} state
   * @param {*} bussinessType
   */
  setBussinessType(state, bussinessType) {
    state.bussinessType = bussinessType
  },
  /**
   * 设置用户信息
   */
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  /**
   * 设置地市编码
   */
  setCityInfo(state, cityInfo) {
    state.cityInfo = cityInfo
  },
  /**
   * @description 设置用户名
   * @param {*} state
   * @param {*} username
   */
  setUsername(state, username) {
    state.username = username
  },
  /**
   * @description 设置头像
   * @param {*} state
   * @param {*} avatar
   */
  setAvatar(state, avatar) {
    state.avatar = avatar
  }
}
const actions = {
  /**
   * @description 获取用户信息
   * **/
  getUserInfo({ commit, dispatch }) {
    return new Promise((resolve, reject) => {
      authApi
        .getUserInfo()
        .then(res => {
          dispatch('getUnitCity', get(res, 'data.orgInfos.0.orgId'))
          commit('setUserInfo', res.data)

          dispatch('getBussinessTypeByOrgId', get(res, 'data.orgInfos.0.orgId'))
          resolve(res.data)
        })
        .catch(err => {
          dispatch('removeCookie')
          dispatch('goToLogin', err.msg)
          reject(err)
        })
    })
  },

  /**
   * @description 获取用户所在城市信息
   * **/
  getUnitCity({ commit, state }, orgId) {
    authApi.getCityLonlat(orgId).then(res => {
      if (res.data) {
        commit('setCityInfo', res.data)
      }
    })
  },
  /**
   *@desc 删除会话cookie 与令牌
   */
  removeCookie() {
    Cookies.remove(config.authKey, {
      path: '/',
      domain: config.domain
    })
    Cookies.remove(config.sessionKey, {
      path: '/',
      domain: config.domain
    })
  },

  /**
   * 退出登录
   */
  handlerLogout({ commit, dispatch }) {
    return new Promise((resolve, reject) => {
      authApi
        .loginout()
        .then(res => {
          dispatch('removeCookie')
          resolve()

          // 跳转页面
          dispatch('goToLogin', res.detail)
        })
        .catch(err => {
          reject(err)
        })
    })
  },
  /**
   * 跳转页面
   */
  goToLogin({ commit }, url) {
    // 跳转页面
    const _url = url && url.includes('http') ? url : config.homePath
    window.location.replace(_url)
    window.parent.location.replace(_url)
  },
  /**
   * @description 登录拦截放行时，设置虚拟角色
   * @param {*} { commit, dispatch }
   */
  setVirtualRoles({ commit, dispatch }) {
    dispatch('acl/setFull', true, { root: true })
    commit('setAvatar', '') // 设置头像图片
    commit('setUsername', '苗栓')
  },
  /**
   * @description 根据组织机构获取业务类型
   * @param {*} { commit, dispatch }
   */
  getBussinessTypeByOrgId({ commit, state }, orgId) {
    const isFetchEnable = true // 是否调用接口获取业务类型
    if (isFetchEnable) {
      if (!orgId) return
      return new Promise((resolve, reject) => {
        authApi.getBussinessType(orgId).then(res => {
          // const bussinessType = (res.data || []).map(i => i.coordinationCode).join()
          const bussinessType = get(res, 'data.0.coordinationCode')
          commit('setBussinessType', bussinessType)
        })
      })
    } else {
      // 测试环境用的业务类型
      const testBussinessType =
        process.env.VUE_APP_PROJECT_MODE === 'jtqg' && process.env.VUE_APP_CURRENTMODE !== 'prod'
          ? 'DISPATCH'
          : undefined
      console.error('testBussinessType', testBussinessType)

      commit(
        'setBussinessType',
        get(state, 'userInfo.orgInfos.0.businessHandleList.0.coordinationCode', testBussinessType)
      )
    }
  }
}
export default { state, getters, mutations, actions }
